﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cstdx.Proto.Ext;

/// <summary>
/// ExCmd1相关工具类
/// </summary>
public static class ExCmd1Helper
{
	/// <summary>
	/// 创建ExCmd1请求包
	/// </summary>
	/// <returns>ExCmd1请求包实例</returns>
	public static ExCmd1Request NewExCmd1Request()
	{
		string hexString = "01 01 48 65 00 01 52 00 52 00 54 24 1f 32 c6 e5 d5 3d fb 41 1f 32 c6 e5 d5 3d fb 41 1f 32 c6 e5 d5 3d fb 41 1f 32 c6 e5 d5 3d fb 41 1f 32 c6 e5 d5 3d fb 41 1f 32 c6 e5 d5 3d fb 41 1f 32 c6 e5 d5 3d fb 41 1f 32 c6 e5 d5 3d fb 41 cc e1 6d ff d5 ba 3f b8 cb c5 7a 05 4f 77 48 ea";
		// 转换16进制字符串为字节数组
		byte[] cmdBytes = HexStringToBytes(hexString);

		var request = new ExCmd1Request();
		// 确保字节数组长度正确（92字节）
		if (cmdBytes.Length == 92)
		{
			request.Cmd = cmdBytes;
		}
		else
		{
			// 如果长度不匹配，复制可用部分
			Array.Copy(cmdBytes, request.Cmd, Math.Min(cmdBytes.Length, 92));
		}

		return request;
	}

	/// <summary>
	/// 创建ExCmd1请求和响应实例
	/// </summary>
	/// <returns>请求实例、响应实例和可能的错误</returns>
	public static (ExCmd1Request request, ExCmd1Response response, Exception error) NewExCmd1()
	{
		try
		{
			var request = NewExCmd1Request();
			var response = new ExCmd1Response();
			return (request, response, null);
		}
		catch (Exception ex)
		{
			return (null, null, ex);
		}
	}

	/// <summary>
	/// 16进制字符串转字节数组（对应Go的HexString2Bytes）
	/// </summary>
	private static byte[] HexStringToBytes(string hexString)
	{
		// 移除所有空格
		hexString = hexString.Replace(" ", "");

		if (hexString.Length % 2 != 0)
		{
			throw new ArgumentException("无效的16进制字符串", nameof(hexString));
		}

		byte[] bytes = new byte[hexString.Length / 2];
		for (int i = 0; i < bytes.Length; i++)
		{
			string hex = hexString.Substring(i * 2, 2);
			bytes[i] = Convert.ToByte(hex, 16);
		}

		return bytes;
	}
}
